import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meal/constant/sizes.dart';
import 'package:meal/model/chat.dart';
import 'package:meal/ui/bubble.dart';
import 'package:meal/utils/colors.dart';
import 'package:meal/utils/styles.dart';
import 'package:meal/utils/tools.dart';

///
/// 在线帮助
///
class HelpChat extends StatefulWidget {
  const HelpChat({Key? key}) : super(key: key);

  @override
  State<HelpChat> createState() => _HelpChatState();
}

class _HelpChatState extends State<HelpChat> with WidgetsBindingObserver {
  double bottom = 0;

  bool show = false;

  late TextEditingController textEditingController;

  late FocusNode focusNode;

  late ScrollController scrollController;

  String content = '';

  List<ChatModel> chats = [];

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
    textEditingController = ToolsUtils.editingController(content);
    focusNode = FocusNode();
    chats.add(ChatModel(header: 'logo.png', msg: '你好！我们可以开始咨询了！'));
    chats.add(ChatModel(header: 'logo.png', msg: '请详细描述一下你的症状！'));
    chats.add(ChatModel(
        header: 'logo.png', msg: '请详细描述一下你的症状！详细描述一下你的症状请详细描述一一下你的症状请详细描述一下你的症状请详细描述一下你的症状'));
    for (var i = 0; i < 10; i++) {
      chats.add(ChatModel(header: 'mine.png', msg: '开始聊天我已经清除->$i', oneself: true));
    }
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance.addPersistentFrameCallback(
      (_) {
        if (bottom == Get.mediaQuery.viewInsets.bottom) {
          return;
        }
        if (Get.mediaQuery.viewInsets.bottom == 0) {
          ///关闭键盘
          show = false;
          bottom = 0;
        } else {
          ///显示键盘
          bottom = Get.mediaQuery.viewInsets.bottom;
        }
        setState(() {});
      },
    );
  }

  @override
  void dispose() {
    focusNode.dispose();
    textEditingController.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ToolsUtils.getDefaultBackgroundColor(),
      appBar: ToolsUtils.getDefaultBrnAppBar('帮助中心'),
      body: customGestureDetector(
          onTap: loseFocus,
          child: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            controller: scrollController,
            padding: EdgeInsets.only(
                left: Sizes.default10,
                right: Sizes.default10,
                top: Sizes.default10,
                bottom: bottom > 1 ? bottom : Sizes.default50),
            child: Column(
              children: buildListChat(context),
            ),
          )),
      bottomSheet: SafeArea(
        top: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.all(Sizes.default5),
              height: Sizes.default50,
              child: Row(
                children: [
                  SizedBox(
                    width: 60,
                    child: Center(
                      child: ToolsUtils.getAssetImageIcon('lng.png', width: 28, height: 28),
                    ),
                  ),
                  Expanded(
                      child: TextField(
                    style: StylesUtils.customTextStyle(color: ColorsUtils.color333),
                    controller: textEditingController,
                    focusNode: focusNode,
                    decoration: InputDecoration(
                      border: const OutlineInputBorder(
                        borderSide: BorderSide.none,
                      ),
                      isCollapsed: true,
                      filled: true,
                      fillColor: ColorsUtils.rgba(242, 242, 242, 1),
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: Sizes.default10, vertical: Sizes.default10),
                      constraints: const BoxConstraints(minHeight: 40),
                    ),
                    onChanged: changeContent,
                    onTap: onFocus,
                  )),
                  InkWell(
                    onTap: addChatMsg,
                    child: Container(
                      width: 48,
                      height: 28,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: ColorsUtils.rgba(47, 143, 255, 0.996078431372549),
                          borderRadius: BorderRadius.circular(Sizes.default5)),
                      margin: const EdgeInsets.symmetric(horizontal: Sizes.default5),
                      child: Text('发送', style: StylesUtils.defaultTextStyle()),
                    ),
                  ),
                  InkWell(
                    onTap: showFace,
                    child: SizedBox(
                      width: 28,
                      height: 28,
                      child: ToolsUtils.getAssetImageIcon('add.png', width: 28, height: 28),
                    ),
                  ),
                ],
              ),
            ),
            ///表情
            Offstage(
              offstage: !show,
              child: SizedBox(
                height: 250,
                child: EmojiPicker(
                    // onEmojiSelected: onEmojiSelected,
                    // onBackspacePressed: onBackspacePressed,
                    textEditingController: textEditingController,
                    config: const Config(
                        emojiSizeMax: 25.0,
                        verticalSpacing: 0,
                        horizontalSpacing: 0,
                        initCategory: Category.RECENT,
                        bgColor: Color(0xFFF2F2F2),
                        indicatorColor: Color(0xff65DAC5),
                        iconColor: Colors.orange,
                        iconColorSelected: Color(0xff65DAC5),
                        backspaceColor: Color(0xff65DAC5),
                        recentsLimit: 28,
                        categoryIcons: CategoryIcons(),
                        buttonMode: ButtonMode.MATERIAL)),
              ),
            )
          ],
        ),
      ),
      resizeToAvoidBottomInset: true,
      extendBody: true,
    );
  }

  List<Widget> buildListChat(BuildContext context) {
    return chats
        .map((chat) => Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(bottom: Sizes.default15),
              child: chat.oneself ? rowSelf(chat) : rowOther(chat),
            ))
        .toList();
  }

  Widget rowOther(ChatModel chat) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          alignment: Alignment.topLeft,
          margin: const EdgeInsets.only(right: Sizes.default10),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(Sizes.default3),
            child: ToolsUtils.getAssetImage(chat.header,
                width: Sizes.default32, height: Sizes.default32),
          ),
        ),
        Flexible(
          child: ClipPath(
            clipper: BubbleClipper(
                direction: BubbleDirection.left, radius: const Radius.circular(Sizes.default6)),
            child: Container(
              padding: const EdgeInsets.only(
                  left: Sizes.default17,
                  right: Sizes.default10,
                  top: Sizes.default10,
                  bottom: Sizes.default10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(Sizes.default6),
                color: ColorsUtils.parseColorFromHexString('#0079FE'),
              ),
              child: Text(chat.msg, style: StylesUtils.defaultTextStyle()),
            ),
          ),
        ),
      ],
    );
  }

  Widget rowSelf(ChatModel chat) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Flexible(
          child: ClipPath(
            clipper: BubbleClipper(
              direction: BubbleDirection.right,
              radius: const Radius.circular(Sizes.default6),
            ),
            child: Container(
              padding: const EdgeInsets.only(
                  left: Sizes.default10,
                  right: Sizes.default17,
                  top: Sizes.default10,
                  bottom: Sizes.default10),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(Sizes.default6),
                  color: ColorsUtils.parseColorFromHexString('#05C160')),
              child: Text(chat.msg, style: StylesUtils.defaultTextStyle()),
            ),
          ),
        ),
        Container(
          alignment: Alignment.topRight,
          margin: const EdgeInsets.only(left: Sizes.default10),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(Sizes.default3),
            child: ToolsUtils.getAssetImage(chat.header,
                width: Sizes.default32, height: Sizes.default32),
          ),
        ),
      ],
    );
  }

  void changeContent(String text) {
    content = text;
    setState(() {});
  }

  void addChatMsg() {
    chats.add(ChatModel(header: 'mine.png', msg: textEditingController.text, oneself: true));
    textEditingController.clear();
    content = '';
    setState(gotoBottom);
  }

  void gotoBottom() {
    Future.delayed(const Duration(milliseconds: 1000), () {
      scrollController.jumpTo(scrollController.position.maxScrollExtent);
    });
  }

  void showFace() {
    show = !show;
    BuildContext? context = Get.key.currentContext;
    if (context != null) {
      FocusScopeNode? currentFocus = FocusScope.of(context);

      /// 键盘是否是弹起状态
      if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
        FocusManager.instance.primaryFocus?.unfocus();
      }
    }
    if (!focusNode.hasFocus) {
      focusNode.requestFocus();
    }
    setState(() {});
  }

  void onEmojiSelected(Category? category, Emoji emoji) {
    textEditingController
      ..text += emoji.emoji
      ..selection =
          TextSelection.fromPosition(TextPosition(offset: textEditingController.text.length));
  }

  void onBackspacePressed() {
    textEditingController
      ..text = textEditingController.text.characters.skipLast(1).toString()
      ..selection =
          TextSelection.fromPosition(TextPosition(offset: textEditingController.text.length));
  }

  void loseFocus() {
    show = false;
    focusNode.unfocus();
    setState(() {});
  }

  void onFocus() {
    show = false;
    setState(() {});
  }

  RawGestureDetector customGestureDetector({
    GestureTapCallback? onTap,
    GestureTapDownCallback? onTapDown,
    Widget? child,
  }) {
    return RawGestureDetector(
      gestures: {
        CustomTapGestureRecognizer:
            GestureRecognizerFactoryWithHandlers<CustomTapGestureRecognizer>(
          () => CustomTapGestureRecognizer(),
          (detector) {
            detector.onTap = onTap;
          },
        )
      },
      child: child,
    );
  }
}

class CustomTapGestureRecognizer extends TapGestureRecognizer {
  @override
  void rejectGesture(int pointer) {
    //不，我不要失败
    super.rejectGesture(pointer);
    //宣布成功
    // super.acceptGesture(pointer);
  }
}
